var express = require('express');
var router = express.Router();
var request = require('request');
var config = require("../config.json");
/* 微信登陆 */
var AppID = config.wechat.appID;
var AppSecret = config.wechat.appSecret;
/*数据库*/
var mysql = require('mysql');
var bodyParser = require("body-parser");
var pool = mysql.createPool(config.mysql);

router.use(bodyParser.json({
    limit: "20000 kb"
}));
router.use(bodyParser.urlencoded({
    parameterLimit: 100000,
    limit: '50mb',
    extended: false
}));

router.get('/wx_login', function(req, res, next) {
    var info = req.query.info;
    var router;
    if (info) {
        router = 'get_wx_access_token?info=' + info;
    } else {
        router = 'get_wx_access_token';
    }
    // 第一步：用户同意授权，获取code

    // 这是编码后的地址 host+app.js定义的路由最后要加/
    var return_uri = 'http%3a%2f%2f10.10.50.70%3a3000%2fuserInfo%2f' + router;

    var scope = 'snsapi_userinfo';
    res.redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + AppID + '&redirect_uri=' + return_uri + '&response_type=code&scope=' + scope + '&state=STATE#wechat_redirect');
});
router.get('/get_wx_access_token', function(req, res, next) {
    // 第二步：通过code换取网页授权access_token
    var code = req.query.code;
    var info = req.query.info;
    request.get({
            url: 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + AppID + '&secret=' + AppSecret + '&code=' + code + '&grant_type=authorization_code',
        },
        function(error, response, body) {
            if (response.statusCode == 200) {
                // 第三步：拉取用户信息(需scope为 snsapi_userinfo)
                var data = JSON.parse(body);
                var access_token = data.access_token;
                var openid = data.openid;

                request.get({
                        url: 'https://api.weixin.qq.com/sns/userinfo?access_token=' + access_token + '&openid=' + openid + '&lang=zh_CN',
                    },
                    function(error, response, body) {
                        if (response.statusCode == 200) {
                            // 第四步：根据获取的用户信息进行对应操作
                            var userinfo = JSON.parse(body);
                            var uid = "'" + userinfo.openid + "'";
                            var name = "'" + userinfo.nickname + "'";
                            var openid = "'" + userinfo.openid + "'";
                            var sex = "'" + userinfo.sex ? userinfo.sex : 3 + "'";
                            var headimgurl = "'" + userinfo.headimgurl + "'";
                            pool.getConnection(function(err, connection) {
                                var sqlf = "SELECT * from user where uid= " + uid;
                                var sql = "INSERT INTO user (name,uid,sex,imgUrl) VALUES (" + name + "," + openid + "," + sex + "," + headimgurl + ")";
                                connection.query(sqlf, function(err, rows, fields) {
                                    if (err) {
                                        console.log(err);
                                    }
                                    if (rows.length == 0) {
                                        connection.query(sql, function(err, rows, fields) {
                                            if (err) {
                                                console.log(err);
                                            }
                                            if (info) {
                                                res.redirect(config.wechat.returnUri + "?id=" + rows.insertId + "&info=" + info);
                                            } else {

                                                res.redirect(config.wechat.returnUri + "?id=" + rows.insertId);
                                            }

                                        });
                                    } else {
                                        if (info) {
                                            res.redirect(config.wechat.returnUri + "?id=" + rows[0].id + "&info=" + info);
                                        } else {
                                            res.redirect(config.wechat.returnUri + "?id=" + rows[0].id);
                                        }

                                    }
                                    connection.release();
                                });

                            });
                        } else {

                        }
                    }
                );
            } else {

            }
        }
    );
});

router.get('/getAuth_code/:id', function(req, res, next) {
    var id = "'" + req.params.id + "'";
    var code = "'" + Math.floor(1000 + Math.random() * (9999 - 1000)) + "'";
    pool.getConnection(function(err, connection) {
        var sql = "UPDATE user set auth_code=" + code + " where id=" + id;

        connection.query(sql, function(err, rows, fields) {
            if (err) {
                console.log(err);
            }
            var data = {
                "code": code
            }
            res.send(data);
            connection.release();
        })
    })

});
router.get('/detailInfo/:id', function(req, res, next) {
    var id = "'" + req.params.id + "'";

    pool.getConnection(function(err, connection) {
        var sql = "select name,imgUrl,uid from user where id=" + id;

        connection.query(sql, function(err, rows, fields) {
            if (err) {
                console.log(err);
            }
            res.send(rows);
            connection.release();
        })
    })

});
//relevance
router.post('/relevance', function(req, res, next) {
    var id = "'" + req.body.id + "'";
    var password = "'" + req.body.password + "'";
    var userName = "'" + req.body.userName + "'";
    pool.getConnection(function(err, connection) {
        var sql = "select userid from user where id=" + id;
        connection.query(sql, function(err, rows, fields) {
            if (err) {
                console.log(err);
            }
            if (rows[0]) {
                res.send(rows);
            } else {
                res.send("等待绑定");
            }
            connection.release();
        })
    })

});
module.exports = router;